<!--
 * Description: ME-塑胶粒成本模型计算
 * Company: 联宝（合肥）电子科技有限公司
 * Author: Qiuxue.Wu
 * Date: 2020/10/12 10:51
-->

<template>
  <div class="plastic-pellets-model">
    <div class="rect">
      <div v-if="fdRowId" class="title">
        <el-link type="primary">{{ commodity }}({{ gcmFunction }})</el-link>
      </div>
      <!--计算按钮-->

      <div class="calcBtn">
        <el-button :loading="isRequesting" size="medium" type="primary" @click="calc">
          {{ $t('button.calc') }}
        </el-button>
      </div>
      <table class="table">
        <tr align="center">
          <td>产品</td>
          <td colspan="4">
            <el-input v-model="model.product" class="td-input"></el-input>
          </td>
          <td>合计</td>
        </tr>
        <!-- 第一大行 -->
        <tr align="center">
          <td rowspan="2">成型材料成本</td>
          <td class="td-must td-option">塑胶粒</td>
          <td class="td-must td-option">塑胶粒单价(kg)</td>
          <td class="td-must">净重(g)</td>
          <td class="td-must">料头重(g)</td>
          <td class="td-calc">材料费用</td>
        </tr>
        <tr align="center">
          <td>
            <el-select
              v-model="model.materialPlasticPellets"
              class="td-select td-option-text"
              clearable
              filterable
              :placeholder="$t('select.placeholder')"
            >
              <el-option
                v-for="item in materialPlasticPelletsList"
                :key="item.id"
                :label="item.supplier"
                :value="item.id"
              />
            </el-select>
          </td>
          <td class="td-not-allowed td-option-text">
            {{ model.materialPlasticPirce }}
          </td>
          <td>
            <el-input v-model="model.materialNetWeight" class="td-input" type="number"></el-input>
          </td>
          <td>
            <el-input v-model="model.materialHeadWeight" class="td-input" type="number"></el-input>
          </td>
          <td class="td-not-allowed td-result">
            {{ model.materialCost }}
          </td>
        </tr>
        <!-- 第二大行 -->
        <tr align="center">
          <td rowspan="2">成型机台成本</td>
          <td class="td-must td-option">机台吨位</td>
          <td class="td-must td-option">机台费率(s)</td>
          <td class="td-must">成型周期(s)</td>
          <td class="td-must">穴数</td>
          <td class="td-calc">机台费用</td>
        </tr>
        <tr align="center">
          <td>
            <el-select
              v-model="model.machineTons"
              class="td-select td-option-text"
              clearable
              filterable
              :placeholder="$t('select.placeholder')"
            >
              <el-option
                v-for="item in machineTonsList"
                :key="item.id"
                :label="item.machineRate"
                :value="item.id"
              />
            </el-select>
          </td>
          <td class="td-not-allowed td-option-text">
            {{ model.machineRate }}
          </td>
          <td>
            <el-input v-model="model.machineMoldingCycle" class="td-input" type="number"></el-input>
          </td>
          <td>
            <el-input v-model="model.machineHoles" class="td-input" type="number"></el-input>
          </td>
          <td class="td-not-allowed td-result">
            {{ model.machineCost }}
          </td>
        </tr>
        <!-- 第三大行 -->
        <tr align="center">
          <td rowspan="2">成型人工成本</td>
          <td class="td-must td-option" colspan="2">人工费率(s)</td>
          <td class="td-must" colspan="2">人力</td>
          <td class="td-calc">人工费用</td>
        </tr>
        <tr align="center">
          <td class="td-not-allowed td-option-text" colspan="2">{{ model.laborRate }}</td>
          <td colspan="2">
            <el-input v-model="model.laborNumbers" class="td-input" type="number"></el-input>
          </td>
          <td class="td-not-allowed td-result">
            {{ model.laborCost }}
          </td>
        </tr>
        <!-- 第四行 热熔铜钉成本 -->
        <tr align="center">
          <td rowspan="2">热熔铜钉成本</td>
          <td class="td-must td-option" colspan="2">热熔费率(pcs)</td>
          <td class="td-must" colspan="2">数量</td>
          <td class="td-calc">热熔费用</td>
        </tr>
        <tr align="center">
          <td class="td-not-allowed td-option-text" colspan="2">
            {{ model.hotMeltRate }}
          </td>
          <td colspan="2">
            <el-input v-model="model.hotMeltNumbers" class="td-input" type="number"></el-input>
          </td>
          <td class="td-not-allowed td-result">
            {{ model.hotMeltCost }}
          </td>
        </tr>
        <!-- 第五行 外观处理成本 -->
        <tr align="center">
          <td rowspan="2">外观处理成本</td>
          <td
            class="td-must td-option"
            style="cursor: pointer"
            @click="paintCapacityVisible = true"
          >
            喷漆
            <img class="point-icon" :src="pointIcon" />
          </td>
          <td class="td-must">印刷</td>
          <td class="td-must">镭雕</td>
          <td class="td-must">其他</td>
          <td class="td-calc">制程成本</td>
        </tr>
        <tr align="center">
          <td class="td-option-text" @dblclick="showSprayInput">
            <el-input
              v-if="isSprayInputShow"
              v-model="model.sprayPaintCost"
              class="td-input"
              type="number"
              @input="handlerPaintCostInput"
            />
            <span v-else>{{ sprayPaintText }}</span>
          </td>
          <td>
            <el-input v-model="model.print" class="td-input" type="number"></el-input>
          </td>
          <td>
            <el-input v-model="model.laserCarving" class="td-input" type="number"></el-input>
          </td>
          <td>
            <el-input v-model="model.others" class="td-input" type="number"></el-input>
          </td>
          <td class="td-not-allowed td-result">
            {{ model.processCost }}
          </td>
        </tr>
        <tr align="center">
          <td class="td-must">损耗(%)</td>
          <td colspan="5">
            <el-input v-model="model.loss" class="td-input" type="number"></el-input>
          </td>
        </tr>
        <tr align="center">
          <td class="td-must">组立</td>
          <td colspan="5">
            <el-input v-model="model.assemble" class="td-input" type="number"></el-input>
          </td>
        </tr>
        <tr align="center">
          <td class="td-must">运包</td>
          <td colspan="5">
            <el-input v-model="model.package" class="td-input" type="number"></el-input>
          </td>
        </tr>
        <tr align="center">
          <td class="td-must td-option">管销/利润(%)</td>
          <td class="td-not-allowed td-option-text" colspan="5">
            {{ model.marketProfit * 100 }}
          </td>
        </tr>
        <tr align="center">
          <td class="td-must">币种</td>
          <td colspan="5">
            <el-select
              v-model="model.currency"
              class="td-select"
              clearable
              filterable
              :placeholder="$t('select.placeholder')"
            >
              <el-option
                v-for="item in $store.getters['dict/dictOptions']('Currency')"
                :key="item.value"
                :label="item.value"
                :value="item.value"
              />
            </el-select>
          </td>
        </tr>
        <tr align="center">
          <td class="td-calc">Total成本</td>
          <td class="td-not-allowed td-result" colspan="5">
            {{ model.totalCost }}
          </td>
        </tr>
      </table>
    </div>

    <!-- 新增 -->
    <BaseDialog
      v-if="paintCapacityVisible"
      title="喷漆"
      :visible.sync="paintCapacityVisible"
      width="80%"
    >
      <PaintCapacity
        :sprayPaint="model.sprayPaint"
        @cancel="paintCapacityVisible = false"
        @setPaintCapacity="setPaintCapacity"
      />
    </BaseDialog>
  </div>
</template>
<script>
import PaintCapacity from './PaintCapacity'

import { modelConfigList } from '@/api/model/config'
import { modelExtraConfigList } from '@/api/model/extra-config'
import { modelComputed, modelComputedFd } from '@/api/model/computed'

export default {
  name: 'MeCostModel',

  components: { PaintCapacity },

  props: {
    commodity: {
      type: String,
      default: ''
    },

    gcmFunction: {
      type: String,
      default: ''
    },

    fdRowId: {
      type: String,
      default: ''
    },

    lastModel: {
      type: Object,
      default: () => {}
    }
  },

  data() {
    return {
      pointIcon: require('@/assets/icons/point.png'),

      paintCapacityVisible: false,

      isRequesting: false,

      model: {
        // 塑胶粒
        materialPlasticPellets: '',

        // 塑胶粒单价
        materialPlasticPirce: '',

        // 机台吨位
        machineTons: '',

        // 人工费率
        laborRate: '',

        // 热熔费率
        hotMeltRate: '',

        // 管销/利润
        marketProfit: '',

        // 喷漆价格
        sprayPaintCost: '',

        // 机台费率(s)
        machineRate: '',

        // 喷漆json
        sprayPaint: [],

        currency: '',

        // 净重
        materialNetWeight: 17,

        // 料头重(g)
        materialHeadWeight: 8,

        // 人力
        laborNumbers: 2,

        // 印刷
        print: 0.03,

        // 镭雕
        laserCarving: 1,

        // others
        others: 1,

        // 运包
        package: 0.05,

        // 损耗
        loss: 5,

        // 热熔铜数量
        hotMeltNumbers: 1,

        // 穴数
        machineHoles: 2,

        // 成型周期
        machineMoldingCycle: 30,

        // 组立
        assemble: 1
      },

      // 配置
      configList: [],

      // 塑胶粒
      materialPlasticPelletsList: [],

      // 机台吨位
      machineTonsList: [],

      isSprayInputShow: false
    }
  },

  computed: {
    sprayPaintText() {
      if (this.model.sprayPaintCost) {
        return this.model.sprayPaintCost
      } else if (this.model.sprayPaint.length > 0) {
        return '已配置'
      } else {
        return '已配置'
      }
    }
  },

  async created() {
    try {
      // 塑胶粒列表
      this.materialPlasticPelletsList = await this.getExtraConfigList('plastic_pellets')

      // 机台吨位
      this.machineTonsList = await this.getExtraConfigList('machine_tonnage')

      if (Object.keys(this.lastModel).length > 0) {
        this.model = this.$deepCopy(this.lastModel)
        this.model.loss = this.model.loss * 100
      } else {
        this.model.currency = 'USD'
      }

      // 配置
      await this.getConfigList()

      // 人工费率
      this.model.laborRate = this.configList.find(
        item => item.configKey === 'labor_rate'
      ).configValue

      // 热熔费率
      this.model.hotMeltRate = this.configList.find(
        item => item.configKey === 'hot_melt_rate'
      ).configValue

      // 管销/利润
      this.model.marketProfit = this.configList.find(
        item => item.configKey === 'management_profit'
      ).configValue

      // 第一次应该反显后台真实的值，不参与数据联动
      this.$watch('model.materialPlasticPellets', function(newVal) {
        const result = this.materialPlasticPelletsList.find(item => item.id === newVal)
        this.model.materialPlasticPirce = result ? result.unit : ''
      })

      this.$watch('model.machineTons', function(newVal) {
        const result = this.machineTonsList.find(item => item.id === newVal)
        this.model.machineRate = result ? result.normalS : ''
      })
    } catch (error) {
      console.log(error)
    }
  },

  methods: {
    showSprayInput() {
      this.isSprayInputShow = true
    },
    setPaintCapacity(val) {
      this.model.sprayPaint = val
      this.isSprayInputShow = false
      this.model.sprayPaintCost = ''
      this.paintCapacityVisible = false
    },
    handlerPaintCostInput() {
      this.model.sprayPaint = []
    },

    async calc() {
      if (this.fdRowId) {
        this.calcFd()
      } else {
        this.calcSimple()
      }
    },

    async calcSimple() {
      try {
        this.isRequesting = true
        const result = await modelComputed(
          {
            costModelGcmFunc: this.gcmFunction,
            costModelCommodityType: this.commodity,
            computedParams: { ...this.model, loss: this.model.loss / 100 }
          },
          { msgSuccess: true, msgError: true }
        )
        this.model = result.data.computedResult
        this.model.loss = this.model.loss * 100
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = false
      }
    },

    async calcFd() {
      try {
        this.isRequesting = true
        const result = await modelComputedFd(
          {
            computedParams: {
              costModelGcmFunc: this.gcmFunction,
              costModelCommodityType: this.commodity,
              computedParams: { ...this.model, loss: this.model.loss / 100 }
            },

            fdRowId: this.fdRowId
          },
          { msgSuccess: true, msgError: true }
        )
        this.model = result.data.computedResult
        this.model.loss = this.model.loss * 100
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = false
      }
    },

    async getConfigList() {
      try {
        const res = await modelConfigList({})
        this.configList = res.data
      } catch (error) {
        console.log(error)
      }
    },

    async getExtraConfigList(configKey) {
      try {
        const result = await modelExtraConfigList({
          configKey: configKey
        })
        const list = []
        result.data.forEach(item => {
          const configValue = JSON.parse(item.configValue)
          list.push({ id: item.id, configKey: item.configKey, ...configValue })
        })
        return list
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.plastic-pellets-model {
  .rect {
    margin: 0 auto;
    width: 900px;
    .calcBtn {
      height: 40px;
      width: 100%;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      margin-bottom: 10px;
    }
  }
  .title {
    text-align: right;
    padding-bottom: 15px;
  }
  .table {
    width: 100%;
    border-collapse: collapse;
    td {
      width: 130px;
      height: 40px;
      overflow: hidden;
      border: 1px solid #ccc;
      padding: 0 10px;
      word-wrap: break-word;
      word-break: normal;
      position: relative;
    }
  }
  .m-top-15 {
    margin-top: 15px;
  }

  .btn {
    margin-top: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .point-icon {
    width: 18px;
    height: 18px;
    transform: translateY(2px);
  }

  .td-must::after {
    content: '*';
    position: absolute;
    top: 2px;
    right: 4px;
    font-size: 18px;
    color: red;
  }

  .td-not-allowed {
    cursor: not-allowed;
  }

  .td-calc {
    background-color: #00b0f0;
  }

  .td-input {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;

    /deep/.el-input__inner {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      border: none;
      text-align: center;
    }
  }

  .td-option {
    background-color: #baefa0;
  }
  .td-option-text {
    color: #f39507;
    font-weight: 700;
    /deep/ .el-input__inner {
      color: #f39507 !important;
      font-weight: 700 !important;
    }
  }

  .td-select {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    /deep/ .el-input {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
    }
    /deep/.el-input__inner {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      border: none;
      text-align: center;
    }
  }

  .td-result {
    color: red;
    background-color: #e0e0e0;
    font-weight: 700;
  }
}
</style>
